package com.ecobell;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {
private static final String TAG = Main.class.getSimpleName();

protected static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
	private Uri imageUri;
	private int lat;
	private int lon;
	
	private TextView mCameraTest;
	private Button mCameraButton;
	
	private LocationManager mLocationManager;
    private LocationProvider mLocationProvider;
    private LocationListener mLocationListener = new LocationListener() {

		@Override
		public void onLocationChanged(Location loc) {
			// TODO Auto-generated method stub
			lat = (int) (loc.getLatitude() * 100000);
			lon = (int) (loc.getLongitude() * 100000);
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
    	
    };
	
	private Handler mRequestHandler = new Handler() {

		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			super.dispatchMessage(msg);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
		}
		
	};
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mCameraTest = (TextView) findViewById(R.id.buttonTest);
        
        mCameraButton = (Button) findViewById(R.id.cameraButton);
        mCameraButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(Main.this, "Taking a picture using the default camera", Toast.LENGTH_LONG);
				
				String fileName = String.format("%d-%d-%d.jpg", System.currentTimeMillis(), lat, lon);
				//
				ContentValues cv = new ContentValues();
				cv.put(MediaStore.Images.Media.TITLE, fileName);
				cv.put(MediaStore.Images.Media.DESCRIPTION, "EcoBell pictures");
				//
				imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
				//
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
				
				startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
			}
        
        });
        
    }


    
    
	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// rather than using GPS_PROVIDER it'd be better if a certain criteria can be provided
		mLocationProvider = mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER);
		// permission to this GPS_PROVDER (FINE_LOCATION) must be added to manifest
		
		if (mLocationProvider != null) {
			mLocationManager.requestLocationUpdates(mLocationProvider.getName(), 3000, 185000, mLocationListener);
		} else {
            Log.e(TAG, "NO LOCATION PROVIDER AVAILABLE");
            Toast.makeText(this,
                "the GPS location provider is not available at this time.",
                Toast.LENGTH_SHORT).show();
            finish();
        }
	}




	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				String display = "Picture has been takes at URI: " + imageUri.getPath() + "\nlocation=("+ lat + ", "+ lon + ")";
				File saved = convertImageUriToFile(imageUri, this);
				try {
					FileInputStream fis = new FileInputStream(saved);
					ArrayList<Byte> read = new ArrayList<Byte>();
					int aByte = -1;
					while ((aByte = fis.read()) != -1) {
						read.add((byte) aByte);
					}
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				display += "\nfile path at " + saved.getPath();
				
				mCameraTest.setText(display);
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
			} else {
				Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
			}
		}
	}
    
	public static File convertImageUriToFile (Uri imageUri, Activity activity)  {
		Cursor cursor = null;
		try {
		    String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
		    cursor = activity.managedQuery( imageUri,
		            proj, // Which columns to return
		            null,       // WHERE clause; which rows to return (all rows)
		            null,       // WHERE clause selection arguments (none)
		            null); // Order-by clause (ascending by name)
		    int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		    int orientation_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
		    if (cursor.moveToFirst()) {
		        String orientation =  cursor.getString(orientation_ColumnIndex);
		        return new File(cursor.getString(file_ColumnIndex));
		    }
		    return null;
		} finally {
		    if (cursor != null) {
		        cursor.close();
		    }
		}
	}

}